using System;
using System.Web;
using System.Diagnostics;
using CKS.EBE.API;
using Microsoft.SharePoint;
using System.Text.RegularExpressions;
using Microsoft.SharePoint.Utilities;

namespace CKS.EBE
{
	public class DefaultUrlProvider : IUrlProvider
	{
		#region IUrlProvider Members

		public bool UrlHandled(string sUrl)
		{
			return sUrl.Contains("/archive/");
		}

		public void RewriteUrl(Uri siteUrl, HttpContext context, SPWeb oWeb, BlogSettings bs)
		{
			if (oWeb.Features[BlogContext.BlogFeatureGUID] == null) return;

			string sUrl = siteUrl.ToString().ToLower();

			HttpContext.Current.Items["ebeRewrittenPath"] = sUrl;

			string sPartial = sUrl.Substring(oWeb.Url.Length);
			string sPageName = siteUrl.Segments[siteUrl.Segments.Length - 1];

			Debug.WriteLine("Rewriting Url: " + sUrl);
			// TO DO 
			if (sPartial.StartsWith("/archive/tags/"))
			{
				RewriteTagUrl(siteUrl, context, oWeb);
			}
			else if (sPartial.StartsWith("/archive/"))
			{
				int res;
				if ((sPartial.Split('/').Length < 6) && int.TryParse(sPageName.Substring(0, 2), out res))
				{
					RewriteMonthUrl(siteUrl, context, oWeb, sPageName.Substring(0, 2), siteUrl.Segments[siteUrl.Segments.Length - 2].Substring(0, 4));
				}
				else
				{
					RewritePostUrl(siteUrl, context, oWeb);
				}
			}
		}

		private static void RewriteMonthUrl(Uri siteUrl, HttpContext context, SPWeb oWeb, string month, string year)
		{
			Debug.WriteLine("Rewriting Month: " + oWeb.ServerRelativeUrl + "Month.aspx?m=" + month + "&y=" + year);
			string sQuery = "?";
			if (!string.IsNullOrEmpty(siteUrl.Query))
			{
				foreach (string sKey in context.Request.QueryString.AllKeys)
				{
					if (sKey.ToLower() != "m" && sKey.ToLower() != "y")
						sQuery += sKey + "=" + context.Request.QueryString[sKey] + "&";
				}
			}
			context.RewritePath(SPUrlUtility.CombineUrl(oWeb.ServerRelativeUrl, "/Month.aspx" + sQuery + "m=" + month + "&y=" + year));
		}

		private static void RewriteTagUrl(Uri siteUrl, HttpContext context, SPWeb oWeb)
		{
			Regex re = new Regex("/.*/archive/tags/(?<title>.*)/default.aspx");
			Match m = re.Match(siteUrl.ToString());

			Trace.WriteLine("Rewriting Tag: " + oWeb.ServerRelativeUrl + "Category.aspx?c=" + m.Groups["title"].Value);

			string sQuery = "?";
			if (!string.IsNullOrEmpty(siteUrl.Query))
			{
				foreach (string sKey in context.Request.QueryString.AllKeys)
				{
					if (sKey.ToLower() != "c" && sKey.ToLower() != "c")
						sQuery += sKey + "=" + context.Request.QueryString[sKey] + "&";
				}
			}

			context.RewritePath(SPUrlUtility.CombineUrl(oWeb.ServerRelativeUrl, "/Category.aspx" + sQuery + "c=" + m.Groups["title"].Value));
		}

		public SPListItem GetPostFromUrlTitle(string urlTitle, SPWeb oWeb)
		{
			return Helper.GetPostFromUrlTitle(urlTitle, oWeb);
		}

		/// <summary>
		/// rewrite url and redirect HttpContext to /Post.aspx{0}id={1}&List={2}&ItemID={1}, SiteUrl.Query, post.id, list.id
		/// </summary>
		/// <param name="siteUrl"></param>
		/// <param name="context"></param>
		/// <param name="oWeb"></param>
		public void RewritePostUrl(Uri siteUrl, HttpContext context, SPWeb oWeb)
		{
			var re = new Regex("/.*/archive/(?<year>.*)/(?<month>.*)/(?<day>.*)/(?<title>.*).aspx");
			Match m = re.Match(siteUrl.ToString());
         string sTitle = m.Groups["title"].Value;
			SPListItem postItem = GetPostFromUrlTitle(sTitle, oWeb);

			if (postItem == null)
			{
				Debug.WriteLine("Post was not found: " + siteUrl);
				//SPUtility.TransferToErrorPage("Sorry page was not found", "Goto the homepage", siteUrl.ToString());
				context.Response.Redirect(oWeb.Url);
				return;
			}

			Debug.WriteLine("Rewriting Post: " + oWeb.ServerRelativeUrl + "Post.aspx?id=" + postItem.ID);
			string sQuery = "?";
			if (!string.IsNullOrEmpty(siteUrl.Query))
			{
				foreach (string sKey in context.Request.QueryString.AllKeys)
				{
					if (sKey.ToLower() != "id")
					{
						sQuery += sKey + "=" + context.Request.QueryString[sKey] + "&";
					}
				}
			}

			string newUrl = SPUrlUtility.CombineUrl(oWeb.ServerRelativeUrl, string.Format("/Post.aspx{0}id={1}&List={2}&ItemID={1}", sQuery, postItem.ID, postItem.ParentList.ID));
			context.RewritePath(newUrl);
		}

		public string createTagUrl(string tag)
		{
			return SPUrlUtility.CombineUrl(SPContext.Current.Web.ServerRelativeUrl, "/archive/tags/" + tag + "/default.aspx");
		}

		public string createMonthUrl(string postDate)
		{
			return SPUrlUtility.CombineUrl(SPContext.Current.Web.ServerRelativeUrl, "/archive/" + postDate.Substring(0, 4) + "/" + postDate.Substring(5, 2) + ".aspx");
		}

		public string createPostUrl(string postDate, string urlTitle, string postID)
		{
			return SPUrlUtility.CombineUrl(
				 SPContext.Current.Web.ServerRelativeUrl,
				 string.Format("/archive/{0}/{1}/{2}/{3}.aspx", postDate.Substring(0, 4), postDate.Substring(5, 2), postDate.Substring(8, 2), urlTitle));
		}

		public string createAbsolutePostUrl(string postDate, string urlTitle, string postID)
		{
			return SPUrlUtility.CombineUrl(SPContext.Current.Web.Url, "/archive/" + postDate.Substring(0, 4) + "/" + postDate.Substring(5, 2) + "/" + postDate.Substring(8, 2) + "/" + urlTitle + ".aspx");
		}

		public void CheckRootUrl(Uri siteUrl, HttpContext context, SPWeb oWeb)
		{
			if (oWeb.Features[BlogContext.BlogFeatureGUID] == null) return;

			BlogSettings bs = new BlogSettings(oWeb);

			string sUrl = siteUrl.ToString().ToLower();
			if (sUrl.Contains("?")) sUrl = sUrl.Substring(0, sUrl.IndexOf("?"));

			if (!sUrl.EndsWith("/") && !sUrl.EndsWith(".aspx")) sUrl += "/";

			if ((sUrl.Length - oWeb.Url.Length <= 1) || (sUrl.StartsWith(oWeb.Url.ToLower() + "/default.aspx")))
			{
				HttpContext.Current.Items["ebeRewrittenPath"] = sUrl;
				Debug.WriteLine("Rewriting: " + oWeb.ServerRelativeUrl + "/" + bs.HomePage);
				context.RewritePath(SPUrlUtility.CombineUrl(oWeb.ServerRelativeUrl, "/" + bs.HomePage));
			}
		}

		#endregion
	}
}
